namespace Text2Rss.Web.Code
{
	#region Using Directives
	using System;
	using System.Collections.Generic;
	using System.Reflection;
	using System.Web;
	using System.Web.Mvc;
	using System.Web.Routing;
	using Castle.MicroKernel.Registration;
	using Castle.Windsor;
	#endregion

	/// <summary>
	/// Windsor Controller Factory
	/// </summary>
	public class WindsorControllerFactory : DefaultControllerFactory
	{
		/// <summary>
		/// Container for controllers
		/// </summary>
		private readonly IWindsorContainer container;

		/// <summary>
		/// Initializes a new instance of the WindsorControllerFactory class
		/// </summary>
		/// <param name="container">Windsor container</param>
		/// <param name="controllersAssemblies">The list of controller assemblies</param>
		public WindsorControllerFactory(IWindsorContainer container, IEnumerable<Assembly> controllersAssemblies)
		{
			this.container = container;
			foreach (var assembly in controllersAssemblies)
			{
				container.Register(
					AllTypes
						.FromAssembly(assembly)
						.BasedOn<IController>()
						.Configure(component => component.LifeStyle.Transient));
			}
		}

		/// <summary>
		/// Releases the controller
		/// </summary>
		/// <param name="controller">Conntroller to release</param>
		public override void ReleaseController(IController controller)
		{
			container.Release(controller);
		}

		/// <summary>
		/// Creates a new controller instance
		/// </summary>
		/// <param name="requestContext">Context of the request</param>
		/// <param name="controllerType">Type of the controller</param>
		/// <returns>Created container</returns>
		protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
		{
			if (controllerType == null)
			{
				throw new HttpException(404, String.Format("Controller of type {0} is not found", controllerType));
			}

			return container.Resolve(controllerType) as IController;
		}
	}
}
